package edu.bluebeanforum.controller;

import edu.bluebeanforum.common.AppResult;
import edu.bluebeanforum.common.ResultCode;
import edu.bluebeanforum.config.AppConfig;
import edu.bluebeanforum.model.Article;
import edu.bluebeanforum.model.ArticleReply;
import edu.bluebeanforum.model.User;
import edu.bluebeanforum.service.IArticleReplyService;
import edu.bluebeanforum.service.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags = "回复接口")
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IArticleReplyService articleReplyService;

    @ApiOperation("回复帖子")
    @GetMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        //获取用户
        HttpSession session=request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if(user.getState()==1){
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //获取帖子信息
        Article article = articleService.selectById(articleId);
        if (article==null||article.getDeleteState()==1){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //构造回复对象
        ArticleReply articleReply =new ArticleReply();
        articleReply.setArticleId(articleId);//要回复的帖子id
        articleReply.setPostUserId(user.getId());//回复的发送者
        articleReply.setContent(content);
        //写入回复
        articleReplyService.create(articleReply);
        return AppResult.success();

    }
    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(
            @ApiParam("帖子id") @RequestParam("articleId")  @NonNull Long articleId){
        //校验帖子是否存在
        Article article=articleService.selectById(articleId);
        if(article==null||article.getDeleteState()==1){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        List<ArticleReply> result = articleReplyService.selectByArticleId(articleId);
        return AppResult.success(result);
    }




}
